﻿#include "websocket.h"

Websocket::Websocket( QObject* parent ) : QObject( parent ) {}

Websocket::~Websocket() {
    m_timer->stop();
    dataRecvWS->close();
    delete m_timer;
    delete dataRecvWS;
}

void Websocket::sendTextMessage( const QByteArray& msg ) {
    if ( getConnectStatus() ) { dataRecvWS->sendBinaryMessage( msg ); }
}

bool Websocket::getConnectStatus() {
    return connectStatus;
}

Point Websocket::getSlamPose() {
    return slam_point;
}

void Websocket::getBasePos()  //设置josn需要发生的数据格式，加入key和value
{
    QJsonObject jsonObject;

    jsonObject.insert( "message_type", "get_base_pos" );
    QJsonDocument jsondocument;
    jsondocument.setObject( jsonObject );
    get_base_pos = jsondocument.toJson();
}

void Websocket::setInitPos( double x, double y, double yaw ) {
    if ( !getConnectStatus() ) { return; }
    QJsonObject jsonObject;

    jsonObject.insert( "message_type", "set_ini_pos" );
    jsonObject.insert( "ini_x", x );
    jsonObject.insert( "ini_y", y );
    jsonObject.insert( "ini_yaw", yaw );

    QJsonDocument jsondocument;
    jsondocument.setObject( jsonObject );
    sendTextMessage( jsondocument.toJson() );
    emit sigSendTips( "set_init_pos_succeed!" );
}

void Websocket::init() {
    m_timer    = new QTimer();
    dataRecvWS = new QWebSocket();
    connect( dataRecvWS, SIGNAL( disconnected() ), this, SLOT( onDisConnected() ), Qt::AutoConnection );
    connect( dataRecvWS, SIGNAL( textMessageReceived( QString ) ), this, SLOT( onTextReceived( QString ) ), Qt::AutoConnection );
    connect( dataRecvWS, SIGNAL( connected() ), this, SLOT( onConnected() ), Qt::AutoConnection );
    connect( m_timer, SIGNAL( timeout() ), this, SLOT( reconnect() ), Qt::AutoConnection );
}

void Websocket::close() {
    connectStatus = false;
    m_timer->stop();
    dataRecvWS->close();
}
void Websocket::createDataRecvWS( const QString& ip, const int& id ) {
    url = "ws://" + ip + ":8012/echo/username=no" + QString::number( id ) + "&src=agv";
    dataRecvWS->open( QUrl( url ) );
    emit sigSendTips( "创建连接!" );
}

void Websocket::reconnect()  //重新连接
{
    dataRecvWS->close();
    dataRecvWS->open( QUrl( url ) );
}

void Websocket::onConnected() {
    connectStatus = true;
    m_timer->stop();
    emit sigSendTips( "连接成功! IP:" + dataRecvWS->peerAddress().toString() );
}

void Websocket::onTextReceived( const QString& msg ) {
    emit sigSendTips( msg );
}

void Websocket::onDisConnected() {
    emit sigSendTips( "CONNECT" );
    connectStatus = false;
    m_timer->start( 3000 ); /*-<当连接失败时，触发重连计时器，设置计数周期为3秒 */
}
